<template>
  <div class="all">
    <div class="slidedown" @click="slide">
      <p class="innerit el-icon-lx-tag"> 上传广告~</p>
    </div>
    <div style="padding: 15px;display: none" id="slideed" check="1">
      <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          ref="upload"
          :limit="limit"
          :on-exceed="moreout"
          :on-change="handleChange"
          :multiple="true"
          style="height: 148px;border: 1px dashed #eaeaea;padding: 5px;margin-top: 10px;">
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img
              class="el-upload-list__item-thumbnail"
              :src="file.url" alt=""
          >
          <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
          <i class="el-icon-zoom-in"></i>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
         </span>
        </div>
      </el-upload>
      <div style="height: 50px;width: 100%;margin-top: 20px;">
        <el-button type="info" style="float: right;" plain @click="upload">上传</el-button>
      </div>
    </div>
    <div class="pic">
      <div class="imgContainer" v-for="item in data" :key="item.id"
           @click="centerDialogVisible=true,getAdById(item.id)" @contextmenu.prevent="delAd(item.id)">
        <img style="height: 100%;width: 100%" :src="item.imgSrc"/>
      </div>
    </div>

    <el-dialog
        title="图片展示"
        :visible.sync="centerDialogVisible"
        width="60%"
        center>
      <div style="width: 80%;height: 80%;margin: 0 auto;">
        <img style="height: 100%;width: 100%" :src="imgSrc"/>
      </div>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>

  </div>
</template>

<script>
import $ from 'jquery'

export default {
  name: "AdPic",
  data: function () {
    return {
      limit: 9,
      disabled: false,
      param: null,
      filearr: [],
      data: [],
      centerDialogVisible: false,
      imgSrc: require("../assets/loading.gif")
    }
  },
  mounted() {
    this.getAllAd()
  },
  methods: {
    delAd(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/admin/delAd/" + id).then(data => {
          if (data.code == 200) {
            this.$message.success("删除成功")
            this.getAllAd()
          } else {
            this.$message.error(data.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async getAdById(id) {
      this.imgSrc = require("../assets/loading.gif")
      await this.$http.get("/admin/selectById/" + id).then(async data => {
        await this.getimg(data.data.coverPath).then(res => {
          this.imgSrc = res
        })
      })
    },
    async getAllAd() {
      await this.$http.get("/admin/getAllAd").then(async data => {
        data = data.data
        for (let i = 0; i < data.length; i++) {
          await this.getimg(data[i].coverPath).then(res => {
            data[i].imgSrc = res
          })
        }
        this.data = data
      })
    },
    slide() {
      let token = window.localStorage.getItem('myToken');
      if (token == null) {
        this.$message.error('请登陆或注册');
        return
      }
      let check = $("#slideed").attr("check");
      if (check == "1") {
        $("#slideed").slideDown();
        $("#slideed").attr("check", "2")
      } else {
        $("#slideed").slideUp();
        $("#slideed").attr("check", "1")
      }
    },
    getimg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/file/img/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    upload() {
      this.param = new FormData()
      this.filearr.forEach((file) => {
        this.param.append(`file`, file) // 把单个文件重命名，存储起来（给后台）
      })
      if (this.param == null) {
        this.$message.error("请提交照片")
        return
      }
      this.$http({
        method: "post",
        url: "/file/insertPicture",
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: this.param
      }).then(data => {
        if (data.code == 200) {
          this.$message.success("上传成功！！")
          this.$refs.upload.clearFiles();
          this.filearr = []
          this.param = null
          $("#slideed").slideUp();
          $("#slideed").attr("check", "1")
          this.getAllAd()
        }
      })
    },
    handleRemove(file) {
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      fileList.splice(index, 1);

      let aList = this.filearr
      let aIndex = aList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      this.filearr.splice(aIndex, 1)
    },
    handleChange(file) {
      const fileObj = file.raw;
      if (file && fileObj) {
        this.filearr.push(fileObj)
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
    moreout() {
      this.$message.warning("最多上传九张照片！")
    },
  }
}
</script>

<style scoped>
.all {
  width: 980px;
  float: right;
}

.pic {
  box-shadow: rgba(0, 0, 0, 0.07) 0px 1px 2px, rgba(0, 0, 0, 0.07) 0px 2px 4px, rgba(0, 0, 0, 0.07) 0px 4px 8px, rgba(0, 0, 0, 0.07) 0px 8px 16px, rgba(0, 0, 0, 0.07) 0px 16px 32px, rgba(0, 0, 0, 0.07) 0px 32px 64px;
  height: 500px;
  width: 100%;
  clear: both;
  padding: 10px;
  border: 1px solid #eaeaea;
  margin-top: 10px;
  border-radius: 10px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.slidedown {
  height: 40px;
  background-color: rgb(241, 248, 239);
  border-radius: 10px;
  cursor: pointer;
  position: relative;
}

.innerit {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #e0c6a7;
}

.imgContainer {
  height: 110px;
  width: 18%;
  margin-left: 15px;
  margin-top: 15px;
  margin-bottom: 15px;
  /*border: 1px dashed #eaeaea;*/
  position: relative;
  box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 3px, rgba(0, 0, 0, 0.24) 0px 1px 2px;
  border-radius: 10px;
  cursor: pointer;
  transition-duration: 0.5s;
}
</style>